package com.sushi.bigblog.filedb;

import java.io.*;

/**
 * User: bianpeng
 * Date: 11-12-19
 */
public class DbEntry {
    public static int ENTRY_LENGTH = 24;
    // 作者
    private int owner;      // 4b
    // 偏移量
    private long offset;    // 4b
    // 数据长度
    private int size;       // 4b
    // 修改时间
    private long time;      // 8b
    // 标志位
    private int flag;       // 4b

    public DbEntry(int owner, long offset, int size, long time, int flag) {
        this.owner = owner;
        this.offset = offset;
        this.size = size;
        this.time = time;
        this.flag = flag;
    }

    public int getOwner() {
        return owner;
    }

    public long getOffset() {
        return offset;
    }

    public int getSize() {
        return size;
    }

    public long getTime() {
        return time;
    }

    public int getFlag() {
        return flag;
    }

    public static DbEntry load(RandomAccessFile input) throws IOException {
        byte[] bytes = new byte[ENTRY_LENGTH];
        int n = input.read(bytes);
        if (n != ENTRY_LENGTH) throw new IOException("index file broken");
        DataInputStream inputStream = new DataInputStream(new ByteArrayInputStream(bytes));

        int owner = inputStream.readInt();
        long offset = inputStream.readInt();
        int size = inputStream.readInt();
        long time = inputStream.readLong();
        int flag = inputStream.readInt();
        return new DbEntry(owner, offset, size, time, flag);
    }

    public static void save(RandomAccessFile output, DbEntry entry) throws IOException {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(ENTRY_LENGTH);
        DataOutputStream outputStream = new DataOutputStream(byteArrayOutputStream);

        outputStream.writeInt(entry.getOwner());
        outputStream.writeInt((int) entry.getOffset());
        outputStream.writeInt(entry.getSize());
        outputStream.writeLong(entry.getTime());
        outputStream.writeInt(entry.getFlag());

        output.write(byteArrayOutputStream.toByteArray());
    }
}
